package com.dddpeter.app.config;

import com.dddpeter.app.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @Override
    protected void doFilterInternal(@org.springframework.lang.NonNull HttpServletRequest request, 
                                    @org.springframework.lang.NonNull HttpServletResponse response, 
                                    @org.springframework.lang.NonNull FilterChain filterChain) throws ServletException, IOException {
        
        String requestPath = request.getRequestURI();
        
        // 跳过不需要认证的路径
        if (isPublicPath(requestPath)) {
            filterChain.doFilter(request, response);
            return;
        }
        
        String authHeader = request.getHeader("Authorization");
        String token = null;
        
        if (authHeader != null) {
            token = jwtUtil.extractTokenFromHeader(authHeader);
        }
        
        if (token != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            if (jwtUtil.validateToken(token)) {
                String username = jwtUtil.getUsernameFromToken(token);
                Long userId = jwtUtil.getUserIdFromToken(token);
                Boolean isAdmin = jwtUtil.getIsAdminFromToken(token);
                
                // 创建认证对象
                UsernamePasswordAuthenticationToken authToken = 
                    new UsernamePasswordAuthenticationToken(
                        username, 
                        null, 
                        isAdmin ? Collections.singletonList(new SimpleGrantedAuthority("ROLE_ADMIN")) : 
                                Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"))
                    );
                
                // 设置用户ID到认证对象中
                authToken.setDetails(userId);
                
                SecurityContextHolder.getContext().setAuthentication(authToken);
            }
        }
        
        filterChain.doFilter(request, response);
    }
    
    private boolean isPublicPath(String path) {
        // 只有登录和注册接口是公开的
        return path.equals("/api/auth/login") || 
               path.equals("/api/auth/register") ||
               path.startsWith("/api/health") || 
               (path.startsWith("/api/") && path.equals("/api/")) ||
               path.startsWith("/assets/") ||
               path.equals("/") ||
               path.equals("/about") ||
               path.equals("/login") ||
               path.equals("/admin") ||
               path.startsWith("/admin/") ||
               path.endsWith(".html") ||
               path.endsWith(".js") ||
               path.endsWith(".css") ||
               path.endsWith(".png") ||
               path.endsWith(".jpg") ||
               path.endsWith(".ico");
    }
}
